<template>
  <div class="has-foot-pb edit">
    <Cell
      title="姓名"
      v-model="formData.customerName"
      divider
      :required="!id"
      :right="false"
      :isInput="!id"
      :maxlength="50"
      input-align="right"
      placeholder="输入姓名"
    />
    <Cell
      title="联系电话"
      v-model="formData.customerPhone"
      divider
      :required="!id"
      :right="false"
      :isInput="!id"
      :maxlength="12"
      input-align="right"
      placeholder="输入联系电话"
    />
    <Cell
      title="意向加盟城市"
      v-model="formData.intendedCity"
      divider
      required
      :maxlength="50"
      :right="false"
      :isInput="true"
      input-align="right"
      placeholder="输入意向加盟城市"
    />
    <FieldSelect
      v-model="formData.agencyCode"
      v-model:label="formData.agencyName"
      title="所属办事处"
      required
      :url="`/app/v1/user/organization/agencies`"
      label-name="name"
      value-name="code"
      method="get"
      clear
    />
    <FieldSelect
      v-model="formData.intendedBusiness"
      title="意向经营业务"
      :url="`/app/v1/mdmService/custDocDef/page`"
      label-name="name"
      value-name="code"
      method="post"
      :params="{ query: { custDocCode: 'QY037' }, type: 0 }"
      :multiple="true"
      clear
    />
    <FieldSelect
      class="other-cell"
      v-model="formData.intendedLevel"
      subTitle="A类：确定与全友合作意向，有合作实力，有合适口岸，可快速签约；
B类：明确与全友合作意向，但可能资金不足或口岸不达标；
C类：有明确投资意向，对全友或其他竞品品牌；"
      title="意向等级"
      :url="`/data-dict/app/v2/dictionary/CTM_INTENTION_LEVEL`"
      label-name="dictName"
      value-name="dictCode"
      method="get"
      :params="dictParams"
      clear
    />
    <FieldSelect
      v-model="formData.investmentManagerId"
      title="招商经理"
      label-name="managerName"
      value-name="id"
      :optionData="managerList"
      :multiple="false"
      clear
    />
    <!--  :url="`/app/v1/ctmInvestmentManager/page`"
      label-name="managerName"
      value-name="id"
      method="post"
      :params="{ query: { enable: '1' }, type: 0 }" -->
    <FieldSelect
      v-model="formData.customerType"
      title="意向客户分类"
      :url="`/data-dict/app/v2/dictionary/CTM_TOBE_CUSTOMER_TYPE`"
      label-name="dictName"
      value-name="dictCode"
      method="get"
      :params="dictParams"
      clear
    />
    <Cell
      title="身份证号"
      v-model="formData.customerIdcard"
      divider
      :right="false"
      :isInput="true"
      input-align="right"
      placeholder="输入身份证号"
    />
    <FieldSelect
      v-model="formData.customerSex"
      title="性别"
      label-name="label"
      value-name="value"
      :optionData="[
        { label: '男', value: 1 },
        { label: '女', value: 0 }
      ]"
      clear
    />
    <Cell
      title="年龄"
      v-model="formData.customerAge"
      divider
      :right="false"
      :isInput="true"
      input-align="right"
      placeholder="输入年龄"
    />
    <Cell title="是否有店面" :custom="true" :right="false">
      <qmp-switch v-model="formData.isHaveShop" :active-value="1" :inactive-value="0">
        <template #background>
          <span class="qmp-switch__background"> {{ formData.isHaveShop ? '是' : '否' }}</span>
        </template>
      </qmp-switch>
    </Cell>
    <Cell
      v-if="formData.isHaveShop"
      title="店面总面积"
      v-model="formData.shopArea"
      divider
      :right="false"
      :isInput="true"
      input-align="right"
      placeholder="输入店面总面积"
      :maxlength="10"
    />
    <Cell title="特别备注" is-column custom divider :right="false">
      <qmp-field v-model="formData.specialRemarks" type="textarea" placeholder="输入内容" class="ctm-text-area" />
    </Cell>
    <Cell title="现经营品牌/行业资历" is-column custom divider :right="false">
      <qmp-field
        v-model="formData.industryQualification"
        type="textarea"
        placeholder="输入内容"
        class="ctm-text-area"
      />
    </Cell>
    <FieldSelect
      v-model="formData.customerSource"
      title="客户来源"
      :url="`/data-dict/app/v2/dictionary/CTM_TOBE_CUSTOMER_DATA_FROM`"
      label-name="dictName"
      value-name="dictCode"
      method="get"
      :params="dictParams"
      clear
    />

    <div :class="['ctm-content-foot', { relative: keyboard.show }]">
      <div class="btn radius-larg ctm-btn-main" @click="onSubmit">确认</div>
    </div>
  </div>
</template>

<script lang="ts">
  import { reactive, toRefs, getCurrentInstance, nextTick } from 'vue'
  import { useRouter, useRoute, onBeforeRouteLeave } from 'vue-router'
  import { useStore } from 'vuex'

  import Cell from '@/components/Cell/index.vue'
  import FieldSelect from '@/components/FieldSelect/index.vue'
  import { initFormData, isChange } from '@/utils'
  import { detailItem, saveItem } from '@/apis/attractInvestment/potentialCustomer'
  import { validIDCard } from '@/utils/validate'
  import GetKeyboardMixin from '@/utils/useKeyboard'
  import { getManagetList } from '@/apis/attractInvestment/leasingManager'

  const none: any[] = [undefined, null, '']
  interface anyObjectModle {
    // id: any
    formData: any
    // dictParams: object
    // keyboard: object
    [key: string]: any
  }
  export default {
    name: 'PotentialCustomerEdit',
    components: { Cell, FieldSelect },
    setup() {
      const $router = useRouter()
      const $route = useRoute()
      const $store = useStore()

      const { proxy }: any = getCurrentInstance()

      const state = reactive<anyObjectModle>({
        id: $route.query.id || '',
        dictParams: { query: { appCode: 'slm', domainCode: 'marketing' }, type: 0 },
        formData: {
          customerIdcard: '',
          customerName: '',
          customerPhone: '',
          agencyCode: '',
          agencyName: '',
          intendedCity: '',
          intendedBusiness: [],
          intendedLevel: '',
          investmentManagerId: '', // 招商经理
          customerType: '',

          customerSex: '',
          customerAge: '',
          isHaveShop: 0,
          shopArea: '',

          specialRemarks: '',
          customerSource: '',
          industryQualification: '',
          channel: '' // 来源渠道
        },
        originalData: '', // 原始数据 用于对比值是否发生变化
        submiting: false,
        isEditBack: false, // 是否是编辑成功后返回
        managerList: [] // 招商经理列表
      })
      state.keyboard = {
        show: false
      }
      state.keyboard = GetKeyboardMixin()

      state.originalData = JSON.stringify(state.formData)
      const getDetail = () => {
        const id = `${state.id}`
        if (!id) return
        detailItem(id).then((res) => {
          // state.detail = res.data || {}
          initFormData(res.data, state.formData)
          state.originalData = JSON.stringify(state.formData)
        })
      }

      const onCancel = () => {
        console.log('onCancel')
      }

      // 阻止返回
      onBeforeRouteLeave((to, from, next) => {
        if (state.isEditBack || isChange(state.formData, state.originalData)) next()
        else {
          proxy.$dialog
            .confirm({
              title: '当前编辑数据未保存，是否确认退出？',
              theme: 'round-button',
              confirmButtonText: '确认',
              cancelButtonText: '取消',
              showCancelButton: true,
              closeOnPopstate: false
            })
            .then(() => {
              next()
            })
            .catch(() => {
              next(false)
            })
        }
      })

      const onSubmit = () => {
        if (state.submiting) return
        const data = {
          id: state.id,
          ...state.formData,
          intendedBusiness: state.formData.intendedBusiness.join(',')
        }

        if (!state.id) {
          if (none.includes(data.customerName)) {
            proxy.$toast('请输入姓名')
            return
          }

          if (none.includes(data.customerPhone)) {
            proxy.$toast('请输入联系电话')
            return
          }

          const regPhone = /^([1]\d{10}|([\(（]?0[0-9]{2,3}[）\)]?[-]?)?([2-9][0-9]{6,7})+(\-[0-9]{1,4})?)$/
          if (!regPhone.test(data.customerPhone)) {
            proxy.$toast('请输入正确的联系电话')
            return
          }
        }

        if (none.includes(data.intendedCity)) {
          proxy.$toast('请选择意向加盟城市')
          return
        }

        if (none.includes(data.agencyCode)) {
          proxy.$toast('请选择所属办事处')
          return
        }

        if (data.customerIdcard && !validIDCard(data.customerIdcard)) {
          proxy.$toast('请输入正确的身份证号')
          return
        }

        // let regAge = /^(?:[1-9][0-9]?|1[01][0-9]|120)$/
        // if (data.customerAge && !regAge.test(data.customerAge)) {
        //   proxy.$toast('年龄输入不合法')
        //   return
        // }
        state.submiting = true
        saveItem(data)
          .then((res: any) => {
            if (res.success === 1) {
              proxy.$toast(data.id ? '编辑成功' : '新增成功')
              proxy.$SimpleEvents.emit('refreshCustomerChangeList')

              nextTick(() => {
                state.isEditBack = true
                $router.goBack()
              })
            }
            state.submiting = false
          })
          .catch((e) => {
            if (e) proxy.$toast(e || (data.id ? '编辑失败' : '新增失败'))
            state.submiting = false
          })
      }

      const loadList = async () => {
        const filtersRaw: object[] = [
          { id: 'enable', property: 'enable', value: 1, operator: '=' },
          { id: 'dr', property: 'dr', value: 0, operator: '=' }
        ]

        const paramsData = {
          page: 1,
          rows: 50,
          sort: 'lastUpdateTime',
          order: 'desc',
          filtersRaw,
          paramsRaw: {},
          sortersRaw: [],
          pageFlag: false
        }
        getManagetList(paramsData).then((res) => {
          const resData = res.data
          state.managerList = resData.records || []
          if (!state.formData.investmentManagerId) {
            const findObj = state.managerList.find((v: any) => v.managerAccount === $store.getters.userInfo.account)
            state.formData.investmentManagerId = (findObj && findObj.id) || ''
          }
        })
      }

      getDetail()
      loadList()
      return {
        ...toRefs(state),
        onCancel,
        onSubmit
      }
    }
  }
</script>

<style lang="less" scoped>
  .edit {
    margin: 0.1rem 0 0.425rem;
  }

  .other-cell {
    /deep/ .sub-label {
      width: 240px;
      white-space: pre-wrap;
    }
  }
</style>
